<template>
  <div>
    <div style="border: 1px solid #ccc; margin-top: 10px">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        mode="simple"
        style="border-bottom: 1px solid #ccc"
      />
      <Editor
        :defaultConfig="editorConfig"
        mode="simple"
        v-model="valueHtml"
        style="height: 400px; overflow-y: hidden"
        @onCreated="handleCreated"
        @onChange="handleChange"
        @onBlur="handleBlur"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css";
import { onBeforeUnmount, ref, shallowRef, onUpdated } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

const props = defineProps({
  value: String,
  onBlur: {
    type: Function,
    default: null,
  },
});
// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref();

onUpdated(() => {
  valueHtml.value = props.value
})

const toolbarConfig = {
  toolbarKeys: [
    "header1",
    "header2",
    "header3",
    "|",
    "bold",
    "underline",
    "italic",
    "through",
    "color",
    "bgColor",
    "|",
    "bulletedList",
    "numberedList",
    "justifyLeft",
    "justifyRight",
    "justifyCenter",
    "insertTable",
    "|",
    "undo",
    "redo"
  ],
};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;

  editor.destroy();
});

// 编辑器回调函数
const handleCreated = (editor: any) => {
  // console.log("created", editor);
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleChange = (editor: any) => {
  // console.log("change:", editor.getHtml());
  props.onBlur && props.onBlur(editor.getHtml())
};
const handleBlur = (editor: any) => {
  // console.log("blur", editor, editor.getHtml());
  // console.log('---props.onBlur---', props);
  props.onBlur && props.onBlur(editor.getHtml())
};
</script>
